package zzjson.rabbitmq.dlx;

import com.rabbitmq.client.*;
import zzjson.rabbitmq.BaseRabbitMq;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.rabbitmq.dlx</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年04月25日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class DLXConsumer {

	/**
	 * 死信队列三种条件：
	 * The message is negatively acknowledged by a consumer using basic.reject or basic.nack with requeue parameter set to false
	 * The message expires due to TTL; or
	 * The message is dropped because its queue exceeded a length limit
	 *
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		Connection conn = BaseRabbitMq.getConn();
		Channel channel = conn.createChannel();

		HashMap<String, Object> argsMap = new HashMap<>();

		// arguments.put("x-expires","9000"); // 设置队列的TTL
		// arguments.put("x-max-length", 4); // 如果设置了队列的最大长度，超过长度时，先入队的消息会被发送到DLX

		//指定
		argsMap.put("x-dead-letter-exchange", "DLX_EXCHANGE");

		channel.queueDeclare("DLX_QUEUE", false, false, false, null);
		//死信队列交换机
		channel.exchangeDeclare("DLX_EXCHANGE", BuiltinExchangeType.TOPIC, false, false, null);

		//绑定死信队列，此队列接受所有死信消息
		channel.queueBind("DLX_QUEUE", "DLX_EXCHANGE", "#");


		//绑定测试队列
		channel.queueDeclare("TEST_DLX_QUEUE", false, false, false, argsMap);

		System.out.println("waiting for message ....");
		// 创建消费者
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
									   byte[] body) throws IOException {
				String msg = new String(body, StandardCharsets.UTF_8);
				System.out.println("Received message : '" + msg + "'");
				// //拒收所有消息，并且不把消息放回去
				// channel.basicNack(envelope.getDeliveryTag(), false, false);
				// //拒收当前消息，并且不把当前消息放回去
				// channel.basicReject(envelope.getDeliveryTag(), false);
			}
		};
		// 开始获取消息
		// String queue, boolean autoAck, Consumer callback
		// channel.basicConsume("TEST_DLX_QUEUE", true, consumer);
		BaseRabbitMq.close(channel, conn);

	}
}